// admin/system/dao/sys_logininfor_dao.go
package dao

import (
	"go-admin1/admin/system/model"
	"go-admin1/internal/infrastructure/database"
	"go-admin1/internal/infrastructure/logger"

	"go.uber.org/zap"
	"gorm.io/gorm"
)

// SysLogininforDao 登录日志数据访问接口
type SysLogininforDao interface {
	Create(logininfor *model.SysLogininfor) error
	GetByID(id int64) (*model.SysLogininfor, error)
	Delete(id int64) error
	List(page, pageSize int) ([]*model.SysLogininfor, int64, error)
	CleanAll() error
}

type sysLogininforDao struct {
	db *gorm.DB
}

// NewSysLogininforDao 创建登录日志数据访问实例
func NewSysLogininforDao() SysLogininforDao {
	return &sysLogininforDao{
		db: database.GetDB(),
	}
}

func (l *sysLogininforDao) Create(logininfor *model.SysLogininfor) error {
	logger.Info("创建登录日志")
	return l.db.Create(logininfor).Error
}

func (l *sysLogininforDao) GetByID(id int64) (*model.SysLogininfor, error) {
	logger.Debug("根据ID获取登录日志", zap.Int64("info_id", id))
	var logininfor model.SysLogininfor
	err := l.db.Where("info_id = ?", id).First(&logininfor).Error
	return &logininfor, err
}

func (l *sysLogininforDao) Delete(id int64) error {
	logger.Info("删除登录日志", zap.Int64("info_id", id))
	return l.db.Where("info_id = ?", id).Delete(&model.SysLogininfor{}).Error
}

func (l *sysLogininforDao) List(page, pageSize int) ([]*model.SysLogininfor, int64, error) {
	logger.Debug("获取登录日志列表", zap.Int("page", page), zap.Int("page_size", pageSize))
	var logininfors []*model.SysLogininfor
	var total int64

	offset := (page - 1) * pageSize
	db := l.db.Model(&model.SysLogininfor{})

	if err := db.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	if err := db.Offset(offset).Limit(pageSize).Order("login_time DESC").Find(&logininfors).Error; err != nil {
		return nil, 0, err
	}

	return logininfors, total, nil
}

func (l *sysLogininforDao) CleanAll() error {
	logger.Info("清空登录日志")
	return l.db.Session(&gorm.Session{AllowGlobalUpdate: true}).Delete(&model.SysLogininfor{}).Error
}
